<template>
	<view class="information-index">
		<view class="top">
			<rf-navbar :title="title" src="../../static/images/observe/add-observe-bg_top.png"
				@click="onBack"></rf-navbar>
			<image class="bg-bottom" :style="{top:navBarHeight}"
				src="../../static/images/observe/add-observe-bg_bottom.png" mode="widthFix"></image>

		</view>
		<view class="information-logo">
			<rf-uploadfile v-model="form.headSculpture"></rf-uploadfile>
		</view>
		<view class="form">
			<u--form :model="form" ref="uForm" labelPosition="top" labelWidth="300rpx" :rules="rules">
				<u-form-item label="孩子姓名" prop="childName" required>
					<view class="cell">
						<view class="icon">
							<image class="icon_img icon-smile"></image>
						</view>
						<u-input v-model="form.childName" placeholder="请输入孩子的姓名"
							prefixIconStyle="font-size: 22px;color: #909399" />
					</view>
				</u-form-item>
				<u-form-item label="性别" prop="childSex" required>
					<view class="sex">
						<view class="man" :class="{highlight:sexIcon == 0}" @click="onclicksex(0)">
							男
							<view class="man-icon" v-if="sexIcon == 0">
								<u-icon name="checkbox-mark" color="#fff" size="20"></u-icon>
							</view>
						</view>
						<view class="man space" :class="{highlight:sexIcon == 1}" @click="onclicksex(1)">
							女
							<view class="man-icon" v-if="sexIcon == 1">
								<u-icon name="checkbox-mark" color="#fff" size="20"></u-icon>
							</view>
						</view>
					</view>
				</u-form-item>
				<u-form-item label="年龄" prop="childAge" @click="showAge = true;" required>
					<view class="cell">
						<view class="icon">
							<image class="icon_img icon-clover"></image>
						</view>

						<u-input v-model="childAge" disabled placeholder="请选择年龄"
							prefixIconStyle="font-size: 22px;color: #909399" />
						<view class="arrow">
							<u-icon slot="right" name="arrow-right"></u-icon>
						</view>
					</view>


				</u-form-item>
				<u-form-item label="出生日期" prop="beBornDt" @click="showEducation = true;">
					<view class="cell">
						<view class="icon">
							<image class="icon_img icon-date"></image>
						</view>
						<u--input v-model="form.beBornDt" disabled disabledColor="#ffffff" placeholder="请选择出生日期"
							border="none"></u--input>
						<view class="arrow">
							<u-icon slot="right" name="arrow-right"></u-icon>
						</view>
					</view>
				</u-form-item>
				<u-form-item label="家长姓名" prop="parentName">
					<view class="cell">
						<view class="icon">
							<image class="icon_img icon-06png"></image>
						</view>
						<u-input v-model="form.parentName" placeholder="请输入家长姓名"
							prefixIconStyle="font-size: 22px;color: #909399" />
					</view>
				</u-form-item>
				<u-form-item label="联系方式" prop="parentPhone">
					<view class="cell">
						<view class="icon">
							<image class="icon_img icon-04png"></image>
						</view>
						<u-input v-model="form.parentPhone" placeholder="请输入联系方式"
							prefixIconStyle="font-size: 22px;color: #909399" />
					</view>
				</u-form-item>
			</u--form>

			<view class="btn" @click="submit">确 定</view>
		</view>


		<view class="popup">
			<!-- 选择出生日期 -->
			<u-datetime-picker title="选择生日" :show="showEducation" v-model="birthday" mode="date" :maxDate="maxDate"
				@confirm="confirmtime1" @cancel="canceltime" cancelColor="#3A3D4B"
				confirmColor="#58C866"></u-datetime-picker>
			<!-- 选择年龄 -->
			<u-picker :show="showAge" :columns="ageList" keyName="name" :defaultIndex="[childAgeIndex]" title="选择年龄"
				cancelColor="#3A3D4B" confirmColor="#58C866" @confirm="ageSelect" @cancel="showAge = false"></u-picker>
		</view>

		<rf-toast :show="showWarn" :isSus="showSus" :title="warning" @click="showWarn = false"></rf-toast>


		<rf-alertBadge :show="alertBadgeShow" :imageUrl="result.imageUrl" :name="result.name" :remark="result.remark"
			@close="alertBadgeHide"></rf-alertBadge>

		<!-- 是否保存为草稿 -->
		<rf-alert :show="draftShow" @close="draftConfirm" @confirm="draftConfirm" title="温馨提示" desc="是否保存为草稿？"
			confirmText="是" cancelText="否"></rf-alert>

		<view class="" v-if="showPage">
			<page-container :show="showPage" :overlay="false" @beforeleave="beforeleave('showPage')"></page-container>
		</view>
	</view>
</template>

<script>
	import {
		addChild,
		upChildInfo,
		getChildInfo,
	} from '@/api/user.js'
	export default {
		data() {
			return {
				statusBarHeight: this.statusBarHeight,
				navBarHeight: this.navBarHeight,
				menuHeight: this.menuHeight,
				menuRight: this.menuRight,
				menuTop: this.menuTop,
				menuBotton: this.menuBotton,

				edit: false, // view title 显示编辑与添加
				StorageDict: {},
				storageCache: {},
				birthday: Number(new Date()), // 日期选择器，弹起的默认值
				maxDate: null, // 日期选择器的最大值

				// 年龄，性别显示控制
				childAge: "三岁",
				childAgeIndex: 5,
				sexIcon: 0,

				tempform: {},
				form: {

					childId: "",
					teacherId: "",
					childName: "",
					childAge: "3",
					childSex: 0,
					kindergartenName: "",
					beBornDt: "",
					parentName: "",
					parentPhone: "",
					headSculpture: ""

				},

				showEducation: false,
				showAge: false,
				type: "add",

				ageList: [
					[{
						'name': '半岁',
						'value': "0.5",
					}, {
						'name': '一岁',
						'value': "1",
					}, {
						'name': '一岁半',
						'value': "1.5",
					}, {
						'name': '两岁',
						'value': "2",
					}, {
						'name': '两岁半',
						'value': "2.5",
					}, {
						'name': '三岁',
						'value': "3",
					}, {
						'name': '三岁半',
						'value': "3.5",
					}, {
						'name': '四岁',
						'value': "4",
					}, {
						'name': '四岁半',
						'value': "4.5",
					}, {
						'name': '五岁',
						'value': "5",
					}, {
						'name': '五岁半',
						'value': "5.5",
					}, {
						'name': '六岁',
						'value': "6",
					}, {
						'name': '六岁半',
						'value': "6.5",
					}, {
						'name': '七岁',
						'value': "7",
					}]
				],
				rules: {
					childName: [{
							validator: (rule, value, callback) => {
								if (value) {
									return RegExp(
										/^[\u4e00-\u9fa5]{1,6}$/
									).test(value)
								} else {
									return true
								}
							},
							message: "姓名不能为英文、数字及特殊字符",
							trigger: "blur",
						},
						{
							required: true,
							message: "孩子姓名不能为空",
							trigger: "blur"
						}
					],
					childSex: [{
						required: true,
						message: '请选择孩子的性别',
					}],
					childAge: [{
						required: true,
						message: '请输入孩子的年龄',
					}],
					parentName: [{
							validator: (rule, value, callback) => {
								if (value) {
									return RegExp(
										/^[\u4e00-\u9fa5]{1,6}$/
									).test(value)
								} else {
									return true
								}
							},
							message: "请输入正确的姓名",
							trigger: "blur",
						},
						{
							required: false,
							message: "家长姓名不能为空",
							trigger: "blur"
						}
					],
					parentPhone: [{
							validator: (rule, value, callback) => {
								if (value) {
									return this.$u.test.mobile(value);
								} else {
									return true
								}
							},
							message: "手机号格式不正确",
							trigger: "blur"
						},
						{
							required: false,
							message: "手机号码不能为空",
							trigger: "blur"
						}
					],

				},

				// 提示信息
				showWarn: false,
				showSus: false,
				warning: "",

				alertBadgeShow: false,
				result: {},

				draftShow: false, // 是否保存为草稿
				showPage: true, //一开始设置为显示
				cache: true, // 是否存为草稿，在发布后，设置为false

			};
		},
		computed: {
			storage() {
				// 将字典转换为字符串并比较
				const strDict1 = JSON.stringify(this.form);
				const strDict2 = JSON.stringify(this.tempform);
				return !(strDict1 === strDict2)
			},
			title() {
				return this.edit ? "编辑孩子" : "添加孩子"
			}
		},
		onReady() {
			this.$refs.uForm.setRules(this.rules)
		},
		onLoad(options) {
			// 限制生日设置 小于当前时间一个月，不能设置未来的时间
			const currentDate = new Date();
			const previousMonth = new Date(currentDate.getFullYear(), currentDate.getMonth() - 1, currentDate.getDate());
			this.maxDate = Number(previousMonth)
			console.log("-----------------");
			console.log(uni.getStorageSync("StorageDict"));
			this.storageCache = uni.getStorageSync("StorageDict")
			console.log("-=--=--=-=--=-=-=--=-" + JSON.stringify(this.storageCache));
			if (!this.storageCache || JSON.stringify(this.storageCache).length <= 0) {
				this.storageCache = {}
				console.log("-----storageCache----");
			}
			console.log(JSON.stringify(this.storageCache));

			let newChildInfo = this.storageCache["newChildInfo"]
			console.log(newChildInfo);
			console.log(JSON.stringify(newChildInfo));
			if (options.item) {
				// 编辑孩子
				this.edit = true; // title 编辑孩子
				// 传入的孩子信息
				const item = JSON.parse(decodeURIComponent(options.item))
				// 缓存的孩子信息
				const cacheChildInfo = this.storageCache[item.childId]
				// 如果缓存不存在，使用传入孩子信息
				if (cacheChildInfo) {
					// 之前的缓存信息
					this.form = cacheChildInfo;
					// 传过来服务器的孩子信息
					this.tempform = item;
				} else {
					this.form = item;
					// 用于对比，是否更改，需要缓存
					this.tempform = JSON.parse(JSON.stringify(item));
				}

				this.type = options.type
				for (var i = 0; i < this.ageList[0].length; i++) {

					var var1 = this.ageList[0][i]
					if (this.form.childAge === var1.value) {
						this.childAge = var1.name;
						this.childAgeIndex = i;
					}
				}
				// 性别
				this.sexIcon = this.form.childSex
				// 选择生日弹起的more值
				this.birthday = this.form.beBornDt

			} else if (newChildInfo) {
				// 新建孩子保存的草稿信息
				this.form = JSON.parse(JSON.stringify(newChildInfo))
				for (var i = 0; i < this.ageList[0].length; i++) {

					var var1 = this.ageList[0][i]
					if (this.form.childAge === var1.value) {
						this.childAge = var1.name;
						this.childAgeIndex = i;
					}
				}
				// 性别
				this.sexIcon = this.form.childSex
				// 选择生日弹起的more值
				this.birthday = this.form.beBornDt

			} else {
				// 添加孩子

				// 年龄生日初始值
				const birthday = new Date(currentDate.getFullYear() - 3, currentDate.getMonth(), currentDate.getDate());
				this.birthday = birthday
				const timeFormat = uni.$u.timeFormat;
				let timeValue = timeFormat(birthday, 'yyyy-mm-dd');
				this.form.beBornDt = timeValue

			}

			this.getInfo()
		},
		methods: {
			beforeleave() {

				this.showPage = false
				if (this.storage && this.cache) {
					this.draftShow = true;
				} else {
					let pages = getCurrentPages();
					if (pages.length > 1) {
						uni.navigateBack();
					}
				}
			},
			onBack() {
				uni.navigateBack()
			},
			draftConfirm(e) {
				// 是否保存为草稿
				if (e) {
					// 临时保存观察草稿
					console.log("缺德鬼");
					// 异步新增本地缓存。
					if (this.edit) {
						this.$set(this.storageCache, this.form.childId, this.form); // 添加新条目
					} else {
						console.log("-----------");
						console.log(this.storageCache);
						console.log(this.form);
						console.log("-==============");
						this.$set(this.storageCache, "newChildInfo", this.form); // 添加新条目
					}
					uni.setStorage({
						key: 'StorageDict',
						data: this.storageCache
					})

				} else {
					// 不保存草稿
					// 清除本地缓存
					if (this.edit) {
						this.$delete(this.storageCache, this.form.childId); // 删除指定条目
					} else {
						this.$delete(this.storageCache, "newChildInfo"); // 删除指定条目
					}
					uni.setStorage({
						key: 'StorageDict',
						data: this.storageCache
					})
				}

				this.draftShow = false
				// 手动执行返回
				uni.navigateBack({
					delta: 1
				})
			},
			alertBadgeHide() {
				this.alertBadgeShow = false;
				uni.navigateBack();
			},
			confirmtime1(e) {

				// 选择生日
				this.showEducation = false

				const timeFormat = uni.$u.timeFormat;
				let timeValue = timeFormat(e.value, 'yyyy-mm-dd');
				this.form.beBornDt = timeValue

				// 计算年龄
				const birthDate = new Date(e.value);
				const currentDate = new Date();
				const monthsDifference = (currentDate.getFullYear() - birthDate.getFullYear()) * 12 + (currentDate
					.getMonth() - birthDate.getMonth());
				// 页面渲染赋值
				this.form.childAge = Math.ceil(monthsDifference / 6) * 0.5;
				for (var i = 0; i < this.ageList[0].length; i++) {

					var var1 = this.ageList[0][i]
					if (this.form.childAge == var1.value) {
						this.childAge = var1.name;
					}
				}

			},
			canceltime() {
				this.showEducation = false
			},
			Back() {
				uni.navigateBack(1);
			},
			formatData(data) {
				if (data.sex == null) {
					data.sex = 0
				}

				return {
					childId: data.childId,
					teacherId: data.teacherId,
					childName: data.childName,
					childAge: data.childAge,
					childSex: data.childSex,
					kindergartenName: data.kindergartenName,
					beBornDt: data.beBornDt,
					parentName: data.parentName,
					parentPhone: data.parentPhone,
					headSculpture: data.headSculpture,
				};
			},
			getInfo() {
				let _that = this
				// getChildInfo().then(res => {
				// 	console.log("res: " + JSON.stringify(res));
				// 	_that.form = _that.formatData(res.data)
				// })
			},

			onclicksex(e) {
				console.log(e);
				this.sexIcon = e;
				this.form.childSex = e;
			},

			ageSelect(e) {
				this.showAge = false;
				this.form.childAge = e.value[0].value;
				this.childAge = e.value[0].name;

				// 根据选择年龄，重新设置 生日默认值
				const currentDate = new Date();
				const previousMonth = new Date(currentDate.getTime() - (this.form.childAge * 365 * 24 * 60 * 60 *
					1000));
				const timeFormat = uni.$u.timeFormat;
				let timeValue = timeFormat(previousMonth, 'yyyy-mm-dd');
				this.form.beBornDt = timeValue

			},
			submit() {
				console.log("this.form.: " + JSON.stringify(this.form));
				uni.removeStorage({
					key: "child_draft"
				})

				this.$refs.uForm.validate()
					.then((res) => {
						console.log("res: " + JSON.stringify(res));
						if (this.type == "update") {
							this.upKidInfo()
						} else {
							this.addKidInfo()
						}

					}).catch((errors) => {

						this.warning = errors[0].message
						this.showSus = false;
						this.showWarn = true
					});
			},
			upKidInfo() {
				upChildInfo(this.form).then(res => {
					this.cache = false
					if (res.code == 200) {
						this.warning = "修改成功"
						this.showSus = true;
						this.showWarn = true
						setTimeout(() => {
							this.showWarn = false
							uni.$emit('refreshChildList', null)
							uni.navigateBack()
						}, 2000)

					} else {
						this.warning = res.message
						this.showSus = false;
						this.showWarn = true
						setTimeout(() => {
							this.showWarn = false
						}, 2000)
					}
				})
			},
			addKidInfo() {
				addChild(this.form).then(res => {
					this.cache = false
					if (res.code == 200) {
						this.warning = "添加成功"
						this.showSus = true;
						this.showWarn = true
						setTimeout(() => {
							this.showWarn = false
							if (res.data.isBadge == 1) {
								this.alertBadgeShow = true;
								this.result = res.data;
							} else {
								uni.$emit('refreshChildList', null)
								uni.navigateBack()
							}
						}, 1000)

					} else {
						this.warning = res.message
						this.showSus = false;
						this.showWarn = true
						setTimeout(() => {
							this.showWarn = false
						}, 2000)
					}
				})
			},
			/**
			 * @param {Object} title 提示内容
			 * @param {Object} sus 成功/失败 icon
			 * @param {Object} sec 显示多少秒，0 的时候需要手动点击
			 */
			loading(title, sus, sec) {
				let _that = this
				_that.warning = title;
				_that.showSus = sus;
				_that.showWarn = true;
				if (sec = 0) return

				setTimeout(() => {
					_that.showWarn = false
				}, sec * 1000)
			}
		}
	};
</script>

<style lang="scss">
	page {
		background-color: #fff;
		position: relative !important;
		top: 0px !important;
	}

	::v-deep.u-input {
		padding: 0 !important;
	}

	::v-deep.u-input__content {
		background-color: #f4f7f9;
		padding: 20rpx 20rpx 20rpx 70rpx;
		border-radius: 10rpx;
	}

	::v-deep.uni-input-input:disabled {
		background-color: #f4f7f9;
	}

	::v-deep.u-form-item__body__right__content {
		// background-color: #f4f7f9;
	}

	::v-deep.u-input {
		background-color: #f4f7f9;
	}

	::v-deep.u-border {
		border-color: #f4f7f9 !important;
	}

	::v-deep.u-form-item__body__left__content__label {
		margin: 0 0 14rpx 0;
		font-weight: 500;
		color: #000000;
		font-size: 32rpx;
	}

	.information-index {
		width: 100%;
		height: 100%;
		background-color: #fff;
		padding-bottom: 80rpx;

		.top {

			height: 250rpx;

			.bg-bottom {
				position: fixed;
				left: 0;
				top: 64px;
				// z-index: 1;
				width: 100%;

				height: 300px;
			}
		}

		.information-logo {
			display: flex;
			justify-content: center;
			align-items: center;
			flex-direction: column;


			.text {
				width: 352rpx;
				height: 48rpx;
				margin-top: 20rpx;
				background-color: #d8f3db;
				border-radius: 24rpx;
				line-height: 48rpx;
				text-align: center;
				font-size: 24rpx;
				color: #27ab55;
			}
		}

		.form {
			position: relative;
			z-index: 990;
			top: 30px;
			padding: 0 40rpx;

			// background-color: #fff;

			.sex {
				display: flex;
				// background-color: #fff;

				.man {
					width: 168rpx;
					height: 88rpx;
					background: #f4f7f9;
					border-radius: 20rpx;
					text-align: center;
					line-height: 88rpx;
					position: relative;


					&.highlight {
						border: 4rpx solid #58c866;
						background: #ffffff;
					}

					&.space {
						margin-left: 50rpx;
					}

					.man-icon {
						background-color: #58c866;
						position: absolute;
						top: -16rpx;
						right: -16rpx;
						border-radius: 50%;
					}
				}
			}

			.cell {
				display: flex;
				align-items: center;

				.icon {
					position: absolute;

					.icon_img {
						position: relative;
						width: 20px;
						height: 20px;
						left: 20rpx;
					}
				}

				.arrow {
					position: absolute;
					right: 20px;
					margin-right: 20rpx;
				}
			}


		}


		.btn {
			margin: 80rpx auto 50rpx;
			width: 94%;
			height: 88rpx;
			background: #58c866;
			border-radius: 44rpx;
			font-size: 32rpx;
			font-weight: 600;
			color: #ffffff;
			line-height: 88rpx;
			text-align: center;
		}

		.popup {
			.u-popup__content {
				position: relative;
				border-radius: 24rpx 24rpx 0 0;
				overflow: hidden;
				padding-bottom: 150rpx;
			}

			.u-picker__view {
				height: 360rpx !important;
			}


			.u-toolbar__wrapper__cancel {
				padding: 0;
				position: absolute;
				left: 100rpx;
				bottom: -78rpx;

				width: 200rpx;
				height: 80rpx;
				display: flex;
				align-items: center;
				justify-content: center;
			}

			.u-toolbar__wrapper__confirm {
				padding: 0;
				position: absolute;
				right: 100rpx;
				bottom: -78rpx;

				width: 200rpx;
				height: 80rpx;
				display: flex;
				align-items: center;
				justify-content: center;
			}
		}
	}
</style>